import dayjs from 'dayjs'
import Vue from 'vue'

export const setStorage = (key, value) => {
  localStorage.setItem(key, JSON.stringify(value))
}

export const getStorage = key => {
  const VALUE = localStorage.getItem(key)
  return VALUE ? JSON.parse(VALUE) : false
}

/**
 *
 * @param {*} time 时间
 * @param {*} format 格式
 */
export const getInitTime = (time, format) => {
  format = format || 'YYYY-MM-DD HH:mm:ss'
  return time ? dayjs(time).format(format) : dayjs().format(format)
}

/**
 *
 * @param {*} e 时间
 * @returns 主要用于查询时间的结束时间默认带 23:59
 */
export const changeTime = e => {
  if (e && e.length) {
    const list = [getInitTime(e[0], 'YYYY-MM-DD HH:mm:ss'), getInitTime(e[1], 'YYYY-MM-DD HH:mm:ss')]

    if (list[1].includes('00:00:00')) {
      list[1] = `${getInitTime(e[1], 'YYYY-MM-DD')} 23:59:59`
    }

    return list
  }
  return []
}

Vue.prototype.$changeTime = changeTime

/**
 * @description 判断ie浏览器
 */
export const isIEBrowser = () => {
  if (!!window.ActiveXObject || 'ActiveXObject' in window) {
    return true
  }
  return false
}

/**
 *
 * @param {*} blobdata 二进制流
 * @param {*} filename 文件名称
 * @description 导出
 */
export const export_blob_to_excel = (blobdata, filename) => {
  const blob = new Blob([blobdata], { type: 'application/octet-stream;charset=utf-8' }) // application/vnd.ms-excel
  const link = document.getElementById('xsllink') // index.html里加了
  link.href = URL.createObjectURL(blob)
  link.setAttribute('download', `${filename}.xlsx`)
  link.click()
  return true
}

export const dowloadFileResFunction = res => {
  console.log(res, 'dowloadFileResFunction')
  if (res.status === 200) {
    if (isIEBrowser()) {
      // ie浏览器
      window.navigator.msSaveBlob(new Blob([res.file], { type: 'application/vnd.ms-excel' }), res.fileName)
    } else {
      export_blob_to_excel(res.file, res.fileName)
    }
  } else {
    this.$message({
      message: '报表导出异常',
      type: 'warning',
    })
  }
}

/**
 * 深拷贝
 */
export const deepCopy = source => {
  // constructor: 其返回值是对函数的引用
  const targetObj = source.constructor === Array ? [] : {}

  for (const keys in source) {
    if (source.hasOwnProperty(keys)) {
      // 引用数据类型
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = source.constructor === Array ? [] : {}
        // 维护层代码
        targetObj[keys] = deepCopy(source[keys])
      } else {
        // 基本数据类型，直接赋值
        targetObj[keys] = source[keys]
      }
    }
  }

  return targetObj
}

/**
 * 筛选类Truthy的参数
 * @param {Object} params 传入原始 params
 */
export function getTruthyParams(params) {
  const newParams = {}

  for (const key in params) {
    const element = params[key]
    const isArray = Array.isArray(element)
    if (isArray && element.every(item => !item)) continue
    if (!isArray && !element) continue

    newParams[key] = params[key]
  }

  return newParams
}
